/**
 * 
 */
package com.desksoft.ecommerce.helper;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkArgument;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanComparator;
import org.apache.commons.collections.comparators.ReverseComparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.desksoft.ecommerce.vo.logistics.SortingVO;
import com.desksoft.utility.pagination.Page;
import com.desksoft.utility.reflect.ReflectUtil;
import com.google.common.collect.Lists;



/***************************************
 * <pre>
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: Aug 19, 2011 12:09:19 PM
 * 创建作者：yejw
 * 文件名称：SortingHelper.java
 * 版本：
 * 功能：
 * 最后修改时间：Aug 19, 2011 12:09:19 PM
 * 修改记录：
 * </pre>
 *****************************************/

public class SortingHelper {

	protected final static Log log = LogFactory.getLog(SortingHelper.class);
	
	protected final String ASC = "asc";
	protected final String DESC = "desc";
	
	private SortingVO sorting;
	
	private Page<Object> page;
	private List<Map<String, Object>> data;

	public SortingHelper(SortingVO sorting) {
		this.sorting = sorting;
		this.page = new Page<Object>();
		initialize();
	}
	
	/**
	 * 排序结果
	 * @return
	 */
	public Page<Object> getResult() {
		List<Object> objs = populates();
		
		this.sort(objs, this.sorting.getOrderBy(), this.sorting.getSord());
		this.page.setRecordsList(objs);
		
		return this.page;
	}
	
	/**
	 * 排序
	 * @param <T>
	 * @param instances
	 * @param sortBy
	 * @param sort
	 */
	@SuppressWarnings("unchecked")
	public <T> void sort(List<T> instances, String sortBy, String sort) {
		Collections.sort(instances, this.ASC.equalsIgnoreCase(sort) 
				? new BeanComparator(sortBy) : new BeanComparator(sortBy, new ReverseComparator()));
	}
	
	/**
	 * 组装实例
	 * @return
	 */
	public List<Object> populates() {
		Object o = null;
		List<Object> objs = Lists.newArrayList();
		
		for (Map<String, Object> props : this.data) {
			o = this.getInstance();
			ReflectUtil.populate(o, props);
			objs.add(o);
		}
		
		return objs;
	}
	
	/**
	 * 实例
	 * @return
	 */
	public Object getInstance() {
		Object o = null;
		try {
			o = Class.forName(sorting.getClazz()).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
		return o;
	}
	
	/**
	 * 
	 */
	private void initialize() {
		checkNotNull(sorting);
		
		page.setPageSize(sorting.getPageSize());
		page.setPageNo(sorting.getPageNo());
		page.setTotalCount(sorting.getTotalCount());
		
		this.data = sorting.getData();
		
		checkNotNull(this.data);
		checkArgument(this.data.size() > 0);
	}
}
